/**
 * 解析字符串
 * @param  {[String]}  templateString  模板字符串
 * @return {Object} 返回AST
 */
function parse (templateString) {
  /* 指针 */
  let index = 0;
  /* 剩余部分 */
  let rest = '';
  let root = '';
  let currentParent = '';
  const stack = [];
  // const stack = [{
  //   children: []
  // }];
  /* 开始标记 */
  const startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/;
  /* 结束标记 */
  const engRegExp = /^\<\/([a-z]+[1-6]?)\>/;
  /* 结束标记前的文本 */
  const wordRegExp = /^([^\<]+)\<\/([a-z]+[1-6]?)\>/;

  /* 删除前后空格 */
  templateString = templateString.trim();
  while (index < templateString.length - 1) {
    rest = templateString.substring(index);
    /* 变量到的这个字符，是不是一个开始标签 */
    if (startRegExp.test(rest)) {
      let [, tag, attrs] = rest.match(startRegExp);
      console.log(tag, attrs);
      // console.log('检测到开始标记', tag);
      if (attrs == undefined) {
        attrs = '';
      }
      index += tag.length + 2 + attrs.length;
      const element = createASTElement(tag, parseAttrs(attrs));
      stack.push(element);

      if (!root) {
        root = element;
      }
      currentParent = element;

    } else if (engRegExp.test(rest)) {
      let tag = rest.match(engRegExp)[1];
      // console.log('检测到结束标记', tag);
      index += tag.length + 3;
      if (stack[stack.length - 1].tag == tag) {
        const element = stack.pop();
        currentParent = stack[stack.length - 1];
        if (currentParent) {
          /* 添加子集的父级 */
          element.parent = currentParent;
          /* 添加父级的子集 */
          currentParent.children.push(element);
        }
      } else {
        throw new Error('标签不匹配');
      }
    } else if (wordRegExp.test(rest)) {
      let content = rest.match(wordRegExp)[1];
      // console.log('检测到文字', content);
      index += content.length;
      /* 文本不为空的情况 */
      if (content.trim().length !== 0) {
        // console.log('检测到文字', content);
        if (!stack[stack.length - 1].hasOwnProperty('children')) {
          stack[stack.length - 1].children = [];
        }
        stack[stack.length - 1].children.push(
          {
            type: 'text',
            content
          }
        );
      }
    }
    else {
      index++;
    }
  }
  return root;
}

/* 解析字符串键值对 */
/**
 * 解析字符串键值对
 *
 * @param   {String}  str  需要解析的字符串
 *
 * @return  {Array}       返回解析结果
 * @example 
 * parseAttrs('id="app" class="container"') =>
 * [{key: 'id', value: 'app'}, {key: 'class', value: 'container'}]
 */
function parseAttrs (str) {
  str = str.trim();
  if (str.length === 0) return [];
  let isMarks = false, point = 0, result = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] != '"') continue;
    isMarks = !isMarks;
    if (!isMarks) {
      result.push(str.substring(point, i + 1).trim());
      point = i + 1;
    }
  }
  /* 键值对 */
  return result.map((item) => {
    let [key, value] = item.split('=');
    return {
      key: key.trim(),
      value: value.trim().replace(/"/g, '')
    }
  });
}

/* 创建AST元素节点 */
function createASTElement (tagName, attrs) {
  return {
    tag: tagName,
    type: 1,
    attrs,
    parent,
    children: []
  }
}

export {
  parse
}